/**
 * @param {Function | string} formatter
 * @return {Function}
 * @Author: Hisun 958306134@qq.com
 * @LastEditors: Hisun 958306134@qq.com
 * @Date: 2024-07-30 21:27:41
 * @Description: 归一化函数
 */
function _formatNormalize(formatter) {
  if (typeof formatter === "function") {
    return formatter;
  }
  if (typeof formatter !== "string") {
    throw new TypeError("formatter must be a string!");
  }
  if (formatter === "date") {
    formatter = "yyyy-MM-dd";
  } else if (formatter === "datetime") {
    formatter = "yyyy-MM-dd HH:mm:ss";
  }

  const formatterFunc = (dataInfo) => {
    const { yyyy, MM, dd, HH, mm, ss, ms } = dataInfo;
    return formatter
      .replaceAll("yyyy", yyyy)
      .replaceAll("MM", MM)
      .replaceAll("dd", dd)
      .replaceAll("HH", HH)
      .replaceAll("mm", mm)
      .replaceAll("ss", ss)
      .replaceAll("ms", ms);
  };

  return formatterFunc;
}

/**
 * @param {Date} date 日期对象
 * @param {*} formatter
 * @param {Boolean} isPadZero
 * @return {*}
 * @Author: Hisun 958306134@qq.com
 * @LastEditors: Hisun 958306134@qq.com
 * @Date: 2024-07-30 21:15:46
 * @Description: 格式化一个日期
 */
function formate(date, formatter, isPadZero = false) {
  formatter = _formatNormalize(formatter);
  const dateInfo = {
    year: date.getFullYear(),
    month: date.getMonth() + 1,
    day: date.getDate(),
    hour: date.getHours(),
    minute: date.getMinutes(),
    second: date.getSeconds(),
    miniSecond: date.getMilliseconds(),
  };
  dateInfo.yyyy = dateInfo.year.toString();
  dateInfo.MM = dateInfo.month.toString();
  dateInfo.dd = dateInfo.day.toString();
  dateInfo.HH = dateInfo.hour.toString();
  dateInfo.mm = dateInfo.minute.toString();
  dateInfo.ss = dateInfo.second.toString();
  dateInfo.ms = dateInfo.miniSecond.toString();
  // 辅助函数, 是否不足10加0
  function _padZero(prop, len) {
    dateInfo[prop] = dateInfo[prop].padStart(len, "0");
  }
  if (isPadZero) {
    _padZero("yyyy", 4);
    _padZero("MM", 2);
    _padZero("dd", 2);
    _padZero("HH", 2);
    _padZero("mm", 2);
    _padZero("ss", 2);
    _padZero("ms", 2);
  }
  // 调用归一化函数
  const dateStr = formatter(dateInfo);
  console.log("..", dateStr);
  return dateStr;
}

// 可能调用的方式

// '2023-4-6'
formate(new Date(), "date");

// '2023-4-6 14:7:41'
formate(new Date(), "datetime");

// '2023-04-06'
formate(new Date(), "date", true);

// '2023-04-06 14:07:41'
formate(new Date(), "datetime", true);

// '2023年04月6日 14:07:41'
formate(new Date(), "yyyy年mm月dd日 HH:mm:ss");
